<template>
  <div class="menu-config-container" v-loading="pageLoading">
    <div class="page-title-container flex" title="组织配置">
      <a-button type="default" @click="back()">返回 </a-button>
    </div>
    <div class="page-body-container">
      <a-empty :image="simpleImage" v-if="treeList.length == 0" />
      <a-row :gutter="20" v-else>
        <!-- 列表 treeList-->
        <a-col
          :xs="24"
          :sm="24"
          :md="12"
          :lg="8"
          :xl="8"
          :xxl="6"
          v-for="(item, index) in treeList"
          :key="item.id"
        >
          <div class="gutter-box flex">
            <div class="header">
              <div class="title">{{ item.orgName }}</div>
            </div>
            <div class="body">
              <a-tree
                checkable
                v-model="checkedKeys[item.id]"
                :default-checked-keys="defaultCheckedKeys[index]"
                :default-expand-all="true"
                :auto-expand-parent="autoExpandParent"
                :tree-data="[item]"
                :selected-keys="selectedKeys"
                :replaceFields="{
                  children: 'childs',
                  title: 'orgName',
                  key: 'id',
                }"
                @check="onCheck"
              />
            </div>
          </div>
        </a-col>
      </a-row>
    </div>
    <div class="footer">
      <a-button @click="back()"> 取消 </a-button>
      <a-button
        type="primary"
        style="margin-left: 10px"
        :disabled="submitDisabled"
        @click="submit()"
      >
        确定
      </a-button>
    </div>
  </div>
</template>

<script>
import {
  queryAllOrgTreeList,
  queryOrgList,
  addOrg,
} from "@/api/user-center/roleManage.js";
import { addAttributeByKey, flatTreeData } from "@/utils";
import { Empty } from "ant-design-vue";
export default {
  data() {
    return {
      autoExpandParent: true,
      selectedKeys: [],
      expandedKeys: [],
      checkedKeys: {},
      defaultCheckedKeys: [],
      //
      pageLoading: false,
      treeList: [],
      hasIds: [],
      submitLoading: true,
      submitDisabled: true,
    };
  },
  beforeCreate() {
    this.simpleImage = Empty.PRESENTED_IMAGE_SIMPLE;
  },
  mounted() {
    Promise.all([this.queryAllOrgTreeList(), this.queryOrgList()]).finally(
      (_) => {
        let { hasIds, treeList } = this;
        treeList.forEach((v, i) => {
          let allKeys = flatTreeData([v], "childs").map((v) => v.id);
          allKeys.forEach((id) => {
            if (hasIds.includes(id)) {
              this.$set(this.checkedKeys, v.id, [
                ...(this.checkedKeys?.[v.id] || []),
                id,
              ]);
            }
          });
        });
        this.checkHasChoosedData();
      }
    );
  },
  methods: {
    //提交
    submit() {
      let { checkedKeys } = this;
      let ids = [];
      let { id = "" } = this.$route.query;
      this.submitLoading = true;
      Object.keys(checkedKeys).forEach((key) => {
        ids.push(...(checkedKeys[key] || []));
      });
      addOrg({
        orgIds: ids.toString(),
        roleId: id,
        ids: "",
      })
        .then((res) => {
          this.$message.success("操作成功！");
          this.back();
        })
        .catch((_) => {
          this.$message.error("操作失败，请稍后重试~");
        })
        .finally((_) => {
          this.submitLoading = false;
        });
    },

    //
    checkHasChoosedData() {
      let { checkedKeys } = this;
      let ids = [];
      Object.keys(checkedKeys).forEach((key) => {
        ids.push(...(checkedKeys[key] || []));
      });
      this.submitDisabled = ids.length == 0;
    },

    onCheck() {
      this.checkHasChoosedData();
    },

    //查询所有组织树列表
    queryAllOrgTreeList() {
      this.pageLoading = true;
      return new Promise((resolve, reject) => {
        queryAllOrgTreeList()
          .then((res) => {
            let { data } = res;
            (data?.result || []).forEach((v) => {
              let item = addAttributeByKey(
                null,
                "scopedSlots",
                { icon: "custom" },
                [v],
                "childs"
              );
              let allKeys = flatTreeData([v], "childs").map((v) => v.id);
              v = item[0];
              v.allKeys = allKeys;
              this.defaultCheckedKeys.push([]);
            });
            setTimeout(() => {
              this.treeList = data?.result || [];
              this.defaultCheckedKeys = [];
              resolve();
            });
          })
          .catch((_) => {
            this.treeList = [];
            reject();
          })
          .finally((_) => {
            this.pageLoading = false;
          });
      });
    },

    //查询已选组织列表
    queryOrgList() {
      let { id = "" } = this.$route.query;
      this.rightLoading = true;
      return new Promise((resolve, reject) => {
        queryOrgList({ id })
          .then((res) => {
            let { data } = res;
            let hasChoosedData = data?.result || [];
            this.hasIds = hasChoosedData.map((v) => v.orgId);
            resolve();
          })
          .catch((_) => {
            this.hasIds = [];
            reject();
          })
          .finally((_) => {
            this.rightLoading = false;
          });
      });
    },

    //返回
    back() {
      this.$router.push({
        path: "/nebula/user-app/roleManage",
      });
    },
  },
};
</script>

<style lang="less">
.menu-config-container {
  height: 100%;
  .flex();
  flex-direction: column;
  box-sizing: border-box;
  padding: 0 0 0 10px;
  .page-title-container {
    height: 46px;
    background: #ffffff;
    justify-content: space-between;
    padding: 0 20px;
    align-items: center;
    margin-bottom: 10px;
    &::before {
      .flex();
      align-items: center;
      content: attr(title);
      font-size: 16px;
      height: 16px;
      border-left: 3px solid var(--primary-color);
      padding-left: 10px;
    }
  }
  .page-body-container {
    flex: 1;
    flex-wrap: wrap;
    padding: 0 10px 0 0;
    /deep/.ant-empty {
      margin: 0;
    }
    .custom-scrollbar();
    .ant-col {
      height: 430px;
      margin-bottom: 20px;
      .gutter-box {
        background: #ffffff;
        border-radius: 4px;
        height: 100%;
        box-sizing: border-box;
        padding: 0 14px 14px 14px;
        flex-direction: column;
        transition: 0.3s;
        &.add {
          padding: 14px;
          cursor: pointer;
          .body {
            .flex();
            align-items: center;
            justify-content: center;
            flex-direction: column;
            color: #999999;
          }
        }

        &:hover {
          //   border: 1px solid #a7bff2;
          box-shadow: 0px 10px 23px 1px rgba(55, 89, 160, 0.15);
          .header {
            .operate {
              visibility: visible;
            }
          }
        }
        .header {
          height: 50px;
          flex-shrink: 0;
          font-size: 15px;
          color: #333;

          .flex();
          align-items: center;
          justify-content: space-between;
          overflow: hidden;
          .title {
            flex: 1;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            font-weight: bold;
          }
          .operate {
            flex-shrink: 0;
            visibility: hidden;
            /deep/.bj-icon {
              cursor: pointer;
              width: 30px;
              height: 30px;
              margin-left: 6px;
              border-radius: 50%;
              .flex();
              align-items: center;
              justify-content: center;
              &:hover {
                background: #f1f2f7;
              }
            }
          }
        }
        .body {
          flex: 1;
          background: #f6f9ff;
          position: relative;
          .custom-scrollbar();
          &::-webkit-scrollbar {
            /*滚动条整体样式*/
            width: 0;
            height: 0;
          }
          .ant-tree {
            li {
              width: 100%;
              .ant-tree-node-content-wrapper {
                width: calc(100% - 60px);
                overflow: hidden;
                .ant-tree-title {
                  display: block;
                  width: 100%;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  white-space: nowrap;
                }
              }
            }
          }
        }
      }
    }
  }
  .footer {
    height: 60px;
    border-top: 1px solid #f3f4f6;
    margin-top: 4px;
    .flex();
    justify-content: center;
    align-items: center;
    background: #fff;
  }
}
</style>
